/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.hires.rest;

import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Log;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.hires.domain.Hires;
import me.zhengjie.modules.hires.domain.vo.PublishHiresVo;
import me.zhengjie.modules.hires.service.HiresService;
import me.zhengjie.modules.hires.service.dto.HiresDto;
import me.zhengjie.modules.hires.service.dto.HiresQueryCriteria;
import me.zhengjie.modules.order.domain.WechatOrder;
import me.zhengjie.modules.order.service.WechatOrderService;
import me.zhengjie.modules.pay.wechat.sdk.WxPayTradeTypeEnum;
import me.zhengjie.modules.publish.service.PublishTypeMoneyService;
import me.zhengjie.modules.publish.service.dto.PublishTypeMoneyDto;
import me.zhengjie.utils.R;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.StringUtils;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.enums.PayTypeEnum;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Objects;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

/**
*
* @author 毛晋辉
* @date 2020-09-06
**/
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "招聘信息管理")
@RequestMapping("/api/hires")
public class HiresController {

    private final HiresService hiresService;
    private final WechatOrderService wechatOrderService;
    private final PublishTypeMoneyService publishTypeMoneyService;
    private final WxPayService wxPayService;





    @Log("提交发布招聘信息")
    @ApiOperation("提交发布招聘信息")
    @PostMapping(value = "/publish")
    public <T> T  publish(HttpServletRequest req ,@Validated @RequestBody PublishHiresVo publishHiresVo)  {



        // 查询支付的金额对应的时间
        int publishTypeMoneyId = publishHiresVo.getPublishTypeMoneyId();
        PublishTypeMoneyDto publishTypeMoneyDto = publishTypeMoneyService.findById(publishTypeMoneyId);


        //插入招聘信息
        String userId = SecurityUtils.getCurrentUserId();
        Hires hires = publishHiresVo.getHires();

        hires.setUserId(userId);
        hires.setStatus(-1);
        hiresService.create(hires);

        // 插入订单信息
        WechatOrder order = new WechatOrder();
        order.setUserId(userId);
        order.setAttach(PayTypeEnum.HIRES.getType());
        order.setAttachId(hires.getId());
        order.setPublishMoneyId(publishTypeMoneyId);

        order.setBody(hires.getTitle());
        order.setSpbillCreateIp(StringUtils.getIp(req));
        order.setTotalFee(publishTypeMoneyDto.getMoney().multiply(new BigDecimal("100")).intValue());
        order.setTradeType(WxPayTradeTypeEnum.JSAPI.getTradeType());
        order.setStatus(0);
        wechatOrderService.create(order);

        // 生成支付所需参数
        WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
        request.setBody(order.getBody());
        request.setOutTradeNo(order.getId());
        request.setAttach(order.getAttach());
        request.setTotalFee(order.getTotalFee());
        request.setTradeType(order.getTradeType());
        request.setSpbillCreateIp(order.getSpbillCreateIp());
        request.setOpenid(SecurityUtils.getCurrentUsername());
        request.setNotifyUrl(wxPayService.getConfig().getPayScoreNotifyUrl());

        try {
//            return new ResponseEntity<>(wxPayService.createOrder(request),HttpStatus.OK);
            return wxPayService.createOrder(request);

        } catch (WxPayException e) {
            e.printStackTrace();
            log.error(e.getCustomErrorMsg(), e);
            throw new BadRequestException(StringUtils.isNotEmpty(e.getCustomErrorMsg()) ? e.getCustomErrorMsg() : StringUtils.isNotEmpty(e.getReturnMsg()) && !e.getReturnMsg().equals("OK") ? e.getReturnMsg() : e.getErrCodeDes());
        }
    }

    @GetMapping("findById")
    @Log("根据id查询招聘信息")
    @ApiOperation("查询招聘信息")
    public ResponseEntity<HiresDto> findHiresById( HiresQueryCriteria resources){
        return new ResponseEntity<HiresDto>(hiresService.findById( resources.getId()) ,HttpStatus.OK);
    }


    /**
     *sort = id,desc
     * @param criteria
     * @param pageable
     * @return
     */
    @GetMapping("listByStatus")
    @Log("根据状态查询招聘信息")
    @ApiOperation("查询招聘信息")
//    @AnonymousAccess
    public ResponseEntity<Object> queryByStatus(HiresQueryCriteria criteria,
                                                 Pageable pageable){

        return new ResponseEntity<>(hiresService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @GetMapping("list")
    @Log("根据状态查询招聘信息")
    @ApiOperation("查询招聘信息")
    public ResponseEntity<Object> queryListByStatus(HiresQueryCriteria criteria,
                                                Pageable pageable){

        return new ResponseEntity<>(hiresService.findAllByStatus(criteria.getStatus(),pageable),HttpStatus.OK);
    }


    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('hires:list')")
    public void download(HttpServletResponse response, HiresQueryCriteria criteria) throws IOException {
        hiresService.download(hiresService.queryAll(criteria), response);
    }



    @GetMapping
    @Log("查询招聘信息")
    @ApiOperation("查询招聘信息")
    @PreAuthorize("@el.check('hires:list')")
    public ResponseEntity<Object> query(HiresQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(hiresService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增招聘信息")
    @ApiOperation("新增招聘信息")
//    @PreAuthorize("@el.check('hires:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody Hires resources){
        return new ResponseEntity<>(hiresService.create(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改招聘信息")
    @ApiOperation("修改招聘信息")
    @PreAuthorize("@el.check('hires:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody Hires resources){
        hiresService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除招聘信息")
    @ApiOperation("删除招聘信息")
    @PreAuthorize("@el.check('hires:del')")
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody Long[] ids) {
        hiresService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}